package com.holly.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.holly.exception.ServiceException;
import com.holly.mapper.ClazzMapper;
import com.holly.mapper.StudentMapper;
import com.holly.pojo.Clazz;
import com.holly.pojo.ClazzQueryParam;
import com.holly.pojo.PageResultData;
import com.holly.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author holly
 * @create 2025-07-02 22:56
 */
@Service
public class ClazzServiceImpl implements ClazzService {
    @Autowired
    private ClazzMapper clazzMapper;
    @Autowired
    private StudentMapper studentMapper;
    @Override
    public PageResultData<Clazz> page(ClazzQueryParam param) {
        //1.设置分页参数
        PageHelper.startPage(param.getPage(), param.getPageSize());
        //2.执行查询
        List<Clazz> clazzList = clazzMapper.list(param);
        clazzList.forEach(clazz -> {
            if(clazz.getBeginDate().isAfter(LocalDate.now())){
                clazz.setStatus("未开班");
            }else if(clazz.getEndDate().isBefore(LocalDate.now())){
                clazz.setStatus("已结课");
            }else {
                clazz.setStatus("已开班");
            }
        });

        //3.解析查询结果，并封装
        Page<Clazz> p = (Page<Clazz>) clazzList;
        return new PageResultData<Clazz>(p.getTotal(), p.getResult());
    }

    @Override
    public void save(Clazz clazz) {
        //保存班级基本信息
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.insert(clazz);

    }

    @Override
    public Clazz getById(Integer id) {
        return clazzMapper.getById(id);
    }

    @Override
    public void update(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.update(clazz);
    }

    @Override
    public List<Clazz> list() {
        List<Clazz> clazzList = clazzMapper.listAllClazz();
        return clazzList;
    }

    @Override
    public void delete(Integer id) {
        //1.查询班级下是否有学员
        List<Integer> studentByClazzId = studentMapper.getStudentByClazzId(id);
        //1.1有学员，提醒“对不起, 该班级下有学生, 不能直接删除"
        if(studentByClazzId.size() > 0){
            throw new ServiceException("对不起, 该班级下有学生, 不能直接删除");
        }else{
            //1.2没有学员，删除班级
            clazzMapper.deleteById(id);
        }
    }


}
